//
//  SettingsController.m
//  GroceryStoryboards
//
//  Created by jose on 16/05/13.
//  Copyright (c) 2013 Jose Luis Lopez. All rights reserved.
//

#import "SettingsController.h"
#import "Constants.h"

@interface SettingsController ()

@end

@implementation SettingsController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    self.screenName = @"Settings Screen";
    
    self.versionLabel.text = [NSString stringWithFormat:@"%@ %@", self.versionLabel.text, [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]];
    
    self.scrollTips.contentSize = CGSizeMake(1280, self.scrollTips.frame.size.height);
    self.scrollOptions.contentSize = CGSizeMake(640, 120);
    
    self.arrayButtons = [NSArray arrayWithObjects:self.euroButton, self.crownButton, self.poundButton, self.dollarButton, self.yenButton, self.wButton, self.zlButton, nil];
    
    [self activeButton];
    
    [self getProducts];
    
    [self reloadView];
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"limited"]) 
        [self.goProButton setHidden:NO];
    else {
        [self.goProButton setHidden:YES];
        [self.proLabel setText:@"You have already purchased the Unlimited version. Have we ever thanked you that? Well, thank you anyways!"];
    }
    
}

-(void)viewWillAppear:(BOOL)animated {
    
    [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseIn animations:^(void) {
       
        self.backLabel.transform = CGAffineTransformMakeRotation(270 * M_PI / 180.0);
        NSLog(@"The x is %f, the y is %f", self.backLabel.frame.origin.x, self.backLabel.frame.origin.y);
        [self.backLabel setFrame:CGRectMake(299.5 - 15, 14.5 - 10,
                                            self.backLabel.frame.size.width, self.backLabel.frame.size.height)];
    }completion:^(BOOL res) {
        
    }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)mailPressed:(UIButton *)sender {

    MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc] init];
    mailComposer.mailComposeDelegate = self;
    [mailComposer setSubject:@"About pricify"];
    [mailComposer setToRecipients:[NSArray arrayWithObject:@"pricifyapp@gmail.com"]];
    [self presentViewController:mailComposer animated:YES completion:nil];
}

- (IBAction)backPressed:(UIButton *)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)facebookPressed:(UIButton *)sender {
    
    NSURL *urlApp = [NSURL URLWithString:@"fb://profile/306848299464869"];
    if (![[UIApplication sharedApplication] canOpenURL:urlApp])
        urlApp = [NSURL URLWithString:@"https://www.facebook.com/306848299464869"];
    
    [[UIApplication sharedApplication] openURL:urlApp];
}

-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{

    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)currencyPressed:(UIButton *)sender {

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setValue:sender.titleLabel.text forKey:kCurrencyKey];
    [defaults synchronize];
    
    [self activeButton];
}

- (IBAction)likePressed:(UIButton *)sender {
    
    if (self.arrayProducts != nil && [self.arrayProducts count] > 0) {
        [self purchaseProduct:@"like"];
    } else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Connecting to the app store..." message:@"Right now we are connecting to the App store, please try again later. Note: Internet connection is required for this." delegate:self cancelButtonTitle:nil otherButtonTitles:@"Ok", nil];
        [alertView show];
    }
}

- (IBAction)lovePressed:(UIButton *)sender {
    
    if (self.arrayProducts != nil && [self.arrayProducts count] > 0) {
        [self purchaseProduct:@"love"];
    } else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Connecting to the app store..." message:@"Right now we are connecting to the App store, please try again later. Note: Internet connection is required for this." delegate:self cancelButtonTitle:nil otherButtonTitles:@"Ok", nil];
        [alertView show];
    }
}

- (void)activeButton {
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *currency = [defaults valueForKey:kCurrencyKey];
    if (!currency) {
        currency = @"€";
        [defaults setValue:@"€" forKey:kCurrencyKey];
        [defaults synchronize];
    }
    
    for (UIButton * button in self.arrayButtons) {
        
        if ([button.titleLabel.text isEqualToString:currency])
            [button setSelected:YES];
        else
            [button setSelected:NO];
    }
}

#pragma mark - CRAP

- (void)getProducts {
    
    NSSet *productIdentifiers = [NSSet setWithObjects:@"com.maniacdeveloper.pricify.like", @"com.maniacdeveloper.pricify.love", nil];
    SKProductsRequest *productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers];
    productsRequest.delegate = self;
    [productsRequest start];
    
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
}

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
    self.arrayProducts = [NSMutableArray arrayWithArray:response.products];
    for (SKProduct *product in self.arrayProducts) {
        NSLog(@"Valid product with price: %@ and id: %@" , product.price, product.productIdentifier);
    }
    
    for (NSString *invalidProductId in response.invalidProductIdentifiers)
        NSLog(@"Invalid product id: %@" , invalidProductId);
}

- (void)purchaseProduct:(NSString *)type {
    
    
    SKProduct *product;
//    product = [self.arrayProducts objectAtIndex:0];
    for (SKProduct *p in self.arrayProducts) {
        if ([p.productIdentifier rangeOfString:type].location != NSNotFound) {
            product = p;
            break;
        }
    }
    
    
    [[[GAI sharedInstance] defaultTracker] send:
     [[GAIDictionaryBuilder createEventWithCategory:@"product_purchased"     // Event category (required)
                                             action:@"button_press"  // Event action (required)
                                              label:product.productIdentifier          // Event label
                                              value:nil] build]];
    
    NSLog(@"Purchasing product with id %@", product.productIdentifier);
    SKPayment * payment = [SKPayment paymentWithProduct:product];
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
    NSLog(@"Paymentquueue method");
    for (SKPaymentTransaction *transaction in transactions)
    {
        switch (transaction.transactionState)
        {
            case SKPaymentTransactionStatePurchased:
                [self finishTransaction:transaction wasSuccessful:YES];
                break;
            case SKPaymentTransactionStateFailed:
                [self finishTransaction:transaction wasSuccessful:NO];
                break;
            case SKPaymentTransactionStateRestored:
                [self finishTransaction:transaction wasSuccessful:YES];
                break;
            default:
                break;
        }
    }
}

- (void)finishTransaction:(SKPaymentTransaction *)transaction wasSuccessful:(BOOL)wasSuccessful
{
    NSLog(@"Finish transation");
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
    if (wasSuccessful) {
        NSLog(@"Purchase done, the transaction id %@", transaction.transactionIdentifier);
        [self updateSettings:transaction.payment.productIdentifier];
    } else{
        NSLog(@"Purchase failed");
    }
}

-(void)updateSettings:(NSString *)productId {
    
    NSLog(@"The purchased product id is %@", productId);
    
//    if ([productId isEqualToString:@"com.maniacdeveloper.pricify.unlimited"]) {
//        
//        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"limited"];
//        [[NSUserDefaults standardUserDefaults] synchronize];
//        
//        [self.goProButton setHidden:YES];
//    }
    
    if ([productId isEqualToString:@"com.maniacdeveloper.pricify.like"]) {
        
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"12i30-9210-39-21939-120-901-3"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
//        [self.goProButton setHidden:YES];
        [self reloadView];
    } else if ([productId isEqualToString:@"com.maniacdeveloper.pricify.love"]) {
        
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"92138021120-390-21"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
//        [self.goProButton setHidden:YES];
        [self reloadView];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    [self getProducts];
}

- (void)reloadView {
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"12i30-9210-39-21939-120-901-3"]) {
        
        [self.likeButton setTitle:@"LIKED, THANKS!" forState:UIControlStateNormal];
    }
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"92138021120-390-21"]) {
        
        [self.loveButton setTitle:@"LOVED, MANY THANKS!" forState:UIControlStateNormal];
    }
}

@end
